package org.example.validation;

import org.example.aanotation.Length;
import org.example.aanotation.Max;
import org.example.aanotation.Min;
import org.example.validation.handlers.LengthValidatorHandler;
import org.example.validation.handlers.MaxValidatorHandler;
import org.example.validation.handlers.MinValidatorHandler;

import java.lang.reflect.Field;

// 最小知道原则  尽可能的在最里面封装
//校验器 用于校验   主要是构造检验链 用校验链校验  这个责任链的门面
public class Validator {

    public void validate(Object bean) throws Exception {
        //校验 拿到要校验的注解 然后校验
        Class<?> beanClass = bean.getClass();

        for (Field field : beanClass.getDeclaredFields()) {
            field.setAccessible(true);

            //返回校验链 避免if else
            ValidatorChain chain = buildValidatorChain(field);

            chain.validate(field.get(bean));

        }


    }


    //构建校验链 也就是把每个都放进去
    private ValidatorChain buildValidatorChain(Field field) {
        ValidatorChain chain = new ValidatorChain();
        //注意这里 他的校验值是动态的 所以要new
        Max max = field.getAnnotation(Max.class);
        if (max != null) {
            chain.addHandler(new MaxValidatorHandler(max.value()));
        }

        Min min = field.getAnnotation(Min.class);
        if (max != null) {
            chain.addHandler(new MinValidatorHandler(min.value()));
        }
        Length length = field.getAnnotation(Length.class);
        if (length != null) {
            chain.addHandler(new LengthValidatorHandler(length.value()));
        }

        return chain;
    }

}
